using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace FanDongping.Stock
{
    public class StockList
    {
        private List<Stock> stocks = new List<Stock>();
        private static string stocklistPath = AppDomain.CurrentDomain.BaseDirectory + "StockList.xml";

        public bool Modified
        {
            get
            {
                bool modified = false;
                foreach (Stock s in stocks)
                {
                    modified |= s.Modified;
                }
                return modified;
            }
            set
            {
                foreach (Stock s in stocks)
                {
                    s.Modified = value;
                }
            }
        }

        public List<Stock> Stocks
        {
            get
            {
                return stocks;
            }
            set { stocks = value; }
        }

        public Stock GetStock(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return null;
            }

            foreach (Stock s in StockData.StockList.Stocks)
            {
                if (s.ID == id)
                {
                    return s;
                }
            }
            return null;
        }

        public bool Save()
        {
            XmlSerializer ser = new XmlSerializer(typeof(StockList));

            FileInfo fi = new FileInfo(stocklistPath);
            if (fi.Exists)
            {
                fi.IsReadOnly = false;
            }

            FileStream fa = fi.OpenWrite();
            fa.SetLength(0);
            XmlTextWriter wtr = new XmlTextWriter(fa, null);

            wtr.Formatting = Formatting.Indented;
            wtr.Indentation = 4;
            wtr.IndentChar = (char)32;

            ser.Serialize(wtr, this);
            wtr.Close();

            this.Modified = false;
            return true;

        }

        public static StockList Load()
        {
            StockList t;
            try
            {
                XmlSerializer r = new XmlSerializer(typeof(StockList));
                XmlTextReader xr = new XmlTextReader(stocklistPath);
                t = (StockList)r.Deserialize(xr);
                xr.Close();
            }
            catch (Exception e)
            {
                t = new StockList();
            }
            t.Modified = false;
            return t;
        }
    }
}
